package com.xinchuang.service.apiutil.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.xinchuang.comment.R;
import com.xinchuang.domain.entity.TestNoticeMainTabale;
import com.xinchuang.entity.Edtion;
import com.xinchuang.entity.EdtionNotice;
import com.xinchuang.entity.api.EditionVo;
import com.xinchuang.manager.TestNoticeMainTabaleService;
import com.xinchuang.mapper.EdtionMapper;
import com.xinchuang.mapper.EdtionNoticeMapper;
import com.xinchuang.service.apiutil.PublicService;
import com.xinchuang.utils.ObjectUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author zkwczx
 * @version 1.0
 * @date 2023/11/1 21:41
 */
@Service
@RequiredArgsConstructor
public class PublicServiceImpl implements PublicService {

    private final EdtionMapper edtionMapper;

    private final EdtionNoticeMapper edtionNoticeMapper;

    private final TestNoticeMainTabaleService testNoticeMainTabaleService;

    @Override
    public R getEdition(EditionVo vo) {
        List<Map<String, Object>> maps = new ArrayList<>();
        JSONObject result = new JSONObject();
        int total = 0;
        String value = edtionMapper.getEditionValue(vo.getId());
        if (StringUtils.isNotBlank(value)) {
            String spl = "V";
            total = Integer.parseInt(value.split(spl)[1]);
            int i = 0;
            if (vo.getPageNum() > 1) {
                i = (vo.getPageNum() - 1) * vo.getPageSize();
            }
            for (int j = vo.getPageSize() * vo.getPageNum(); j > i; j--) {
                List<Edtion> editionList = edtionMapper.getEditionList("V" + j, vo.getId());
                Map<String, Object> map = new HashMap<>();
                if (CollectionUtil.isNotEmpty(editionList)) {
                    StringBuffer sb = new StringBuffer();
                    for (Edtion record : editionList) {
                        map.computeIfAbsent("edition", k -> record.getEdition());
                        map.computeIfAbsent("updateTime", k -> DateUtil.format(record.getCreateTime(), "yyyy-MM-dd"));
                        map.computeIfAbsent("updateBy", k -> record.getPerson());
                        if (StringUtils.isBlank(record.getKeyName()) && "删除".equals(record.getKeyValue())) {
                            sb.append("删除一条摸具工号为");
                            sb.append("'" + record.getBaseValue() + "'");
                            sb.append("的试模计划;");
                        } else if (StringUtils.isBlank(record.getBaseValue()) && StringUtils.isNotBlank(record.getUpdateValue())) {
                            sb.append("新增");
                            sb.append("'" + record.getKeyValue() + "'");
                            sb.append("为'" + record.getUpdateValue() + "';");
                        } else {
                            sb.append("将");
                            sb.append("'" + record.getKeyValue() + "'");
                            sb.append("从'" + record.getBaseValue() + "'");
                            sb.append("修改为'" + record.getUpdateValue() + "';");
                        }
                    }
                    map.put("updateContent", sb.toString());
                    maps.add(map);
                } else {
                    TestNoticeMainTabale mainTabale = testNoticeMainTabaleService.getById(vo.getId());
                    if (ObjectUtil.isNotEmpty(mainTabale)) {
                        if (mainTabale.getEdition() >= j) {
                            map.put("edition", "V" + j);
                            map.put("updateTime", "");
                            map.put("updateBy", "");
                            map.put("updateContent", "暂无更新内容");
                            maps.add(map);
                        }
                    }
                }
            }
        } else {
            TestNoticeMainTabale mainTabale = testNoticeMainTabaleService.getById(vo.getId());
            if (ObjectUtil.isNotEmpty(mainTabale) && mainTabale.getEdition() > 0) {
                for (int i = mainTabale.getEdition(); i > 0; i--) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("edition", "V" + i);
                    map.put("updateTime", "");
                    map.put("updateBy", "");
                    map.put("updateContent", "暂无更新内容");
                    maps.add(map);
                }
            }
        }
        result.put("totalNum", total);
        result.put("pageNum", vo.getPageNum());
        result.put("pageSize", vo.getPageSize());
        result.put("dataList", maps);

//        Page page = new Page(vo.getPageNum(), vo.getPageSize());
//        IPage<Edtion> iPage = edtionMapper.getEdition(page, vo.getId());
//        if (CollectionUtil.isNotEmpty(iPage.getRecords())) {
//            Map<String, Object> map;
//            for (Edtion record : iPage.getRecords()) {
//                map = new HashMap<>();
//                map.put("edition", record.getEdition());
//                map.put("updateTime", DateUtil.format(record.getCreateTime(), "yyyy-MM-dd"));
//                map.put("updateBy", record.getPerson());
//                StringBuffer sb = new StringBuffer();
//                if (StringUtils.isBlank(record.getKeyName()) && "删除".equals(record.getKeyValue())) {
//                    sb.append("删除一条摸具工号为");
//                    sb.append("'" + record.getBaseValue() + "'");
//                    sb.append("的试模计划");
//                } else if (StringUtils.isBlank(record.getBaseValue()) && StringUtils.isNotBlank(record.getUpdateValue())) {
//                    sb.append("新增");
//                    sb.append("'" + record.getKeyValue() + "'");
//                    sb.append("为'" + record.getUpdateValue() + "'");
//                } else {
//                    sb.append("将");
//                    sb.append("'" + record.getKeyValue() + "'");
//                    sb.append("从'" + record.getBaseValue() + "'");
//                    sb.append("修改为'" + record.getUpdateValue() + "'");
//                }
//                map.put("updateContent", sb.toString());
//                maps.add(map);
//            }
//        }
//        result.put("totalNum", page.getTotal());
//        result.put("pageNum", page.getCurrent());
//        result.put("pageSize", page.getSize());
//        result.put("dataList", maps);
        return R.data(result);
    }

    @Override
    public R getEditionNotice(EditionVo vo) {
        JSONObject result = new JSONObject();
        List<Map<String, Object>> resultList = new ArrayList<>();
        // 计算起始索引
        int startIndex = Math.max((vo.getPageNum() - 1) * vo.getPageSize(), 0);
        // 计算结束索引（不包含）
        int endIndex = startIndex + vo.getPageSize();
        List<EdtionNotice> editionList = edtionNoticeMapper.getEditionList(vo.getId());
        List<Map.Entry<String, List<EdtionNotice>>> dataList = editionList.stream()
                .collect(Collectors.groupingBy(EdtionNotice::getEdition))
                .entrySet().stream()
                .sorted(Map.Entry.<String, List<EdtionNotice>>comparingByKey().reversed())
                .collect(Collectors.toList());

        if (startIndex <= dataList.size() && endIndex <= dataList.size()) {
            // 截取范围内的数据
            dataList = dataList.subList(startIndex, endIndex);
            for (Map.Entry<String, List<EdtionNotice>> entry : dataList) {
                List<EdtionNotice> list = entry.getValue();
                Map<String, Object> map = new HashMap<>();
                StringBuffer sb = new StringBuffer();
                list.forEach(record -> {
                    map.computeIfAbsent("edition", k -> record.getEdition());
                    map.computeIfAbsent("updateTime", k -> DateUtil.format(record.getCreateTime(), "yyyy-MM-dd"));
                    map.computeIfAbsent("updateBy", k -> record.getPerson());
                    if (StringUtils.isBlank(record.getKeyName()) && "删除".equals(record.getKeyValue())) {
                        sb.append("删除一条摸具工号为");
                        sb.append("'" + record.getBaseValue() + "'");
                        sb.append("的试模计划;");
                    } else if (StringUtils.isBlank(record.getBaseValue()) && StringUtils.isNotBlank(record.getUpdateValue())) {
                        sb.append("新增");
                        sb.append("'" + record.getKeyValue() + "'");
                        sb.append("为'" + record.getUpdateValue() + "';");
                    } else {
                        sb.append("将");
                        sb.append("'" + record.getKeyValue() + "'");
                        sb.append("从'" + record.getBaseValue() + "'");
                        sb.append("修改为'" + record.getUpdateValue() + "';");
                    }
                    map.put("updateContent", sb.toString());
                });
                resultList.add(map);
            }
        }


        result.put("totalNum", resultList.size());
        result.put("pageNum", vo.getPageNum());
        result.put("pageSize", vo.getPageSize());
        result.put("dataList", resultList);
        return R.data(result);
    }

}
